package com.nai365.nart.pay.service.impl;

import cn.hutool.core.codec.Rot;
import com.alibaba.fastjson15.JSON;
import com.alibaba.fastjson15.JSONObject;
import com.nai365.nart.common.core.constant.SecurityConstants;
import com.nai365.nart.common.core.util.R;
import com.nai365.nart.member.entity.Member;
import com.nai365.nart.member.feign.RemoteMemberService;
import com.nai365.nart.pay.entity.Order;
import com.nai365.nart.pay.entity.PayOnBehalf;
import com.nai365.nart.pay.entity.Payee;
import com.nai365.nart.pay.entity.ProductDetail;
import com.nai365.nart.pay.service.PayService;
import com.nai365.nart.pay.vo.PayOnBehalfRetuenVo;
import com.nai365.nart.pay.vo.PayOrderResVo;
import com.upay.sdk.ConfigurationUtils;
import com.upay.sdk.entity.Payer;
import com.upay.sdk.entity.TransferDomesticPayee;
import com.upay.sdk.executer.ResultListenerAdpater;
import com.upay.sdk.onlinepay.builder.OrderBuilder;
import com.upay.sdk.onlinepay.executer.OnlinePayOrderExecuter;
import com.upay.sdk.transferDomestic.builder.QueryBuilder;
import com.upay.sdk.transferDomestic.builder.SingleOrderBuilder;
import com.upay.sdk.transferDomestic.executer.TransferDomesticSingleOrderExecuter;
import lombok.AllArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 支付项
 */
@Service
@AllArgsConstructor
public class PayServiceImpl implements PayService {

	private static final String MERCHANT_ID = "894363429";

//	private static final String NOTIFY_URL = "https://nice.nssrs.com/api/shou_xin/notify/";
	private static final String NOTIFY_URL = "http://112.74.60.53:9999/pay/pay/orderPayRes";

//	private static final String CALL_BACKURL = "https://nice.nssrs.com/";
	private static final String CALL_BACKURL = "http://112.74.60.53:9999/";

	private static final String ORDER_CURRENCY = "CNY";


	private static final String REPORT_SERIAL_NO = "89436342902004";

	/**
	 * 提现的回调
	 */
	private static final String PAY_ON_BEHALF_NOTIFY_URL="http://112.74.60.53:9999/pay/pay/payOnBehalfRes";

	private final RemoteMemberService remoteMemberService;

	@Override
	public String genPayUrl(Order order) {

		ConfigurationUtils.setProperty(MERCHANT_ID + ".client.private.key.password","cl88888888");

		OrderBuilder builder = new OrderBuilder(MERCHANT_ID);
		Payer payer = new Payer();
		//String requestId= UUID.randomUUID().toString().replace("-","");
		builder.setRequestId(order.getRequestId())
				//.setRequestId(requestId)
				.setOrderAmount(order.getOrderAmount())
				.setPaymentModeCode("BANK_CARD-EXPRESS_DEBIT")
				.setOrderCurrency(ORDER_CURRENCY)
				.setNotifyUrl(NOTIFY_URL)
				.setCallbackUrl(CALL_BACKURL)
				.setPayer(payer)
				.setReportSerialNo(REPORT_SERIAL_NO);
		ProductDetail productDetails = order.getProductDetails();

		com.upay.sdk.entity.ProductDetail detail=new com.upay.sdk.entity.ProductDetail();
		detail.setName(productDetails.getName());
		detail.setQuantity(productDetails.getQuantity());
		detail.setAmount(productDetails.getAmount());
		//com.upay.sdk.entity.ProductDetail detail = BeanUtil.copyProperties(productDetails, com.upay.sdk.entity.ProductDetail.class);
		builder.addProductDetail(detail);

		String url = payOrder(builder);
		return url;
	}


	private String payOrder(OrderBuilder builder) {

		final String[] url = {""};
		OnlinePayOrderExecuter executer = new OnlinePayOrderExecuter();

		System.setProperty("https.protocols", "TLSv1.2,TLSv1.1,SSLv3");
		executer.bothOrder(builder, new ResultListenerAdpater() {
//			/**
//			 * 提交成功，不代表支付成功
//			 */
//			@Override
//			public void success(JSONObject jsonObject) {
//				System.out.println("success jsonObject:[" + jsonObject + "]");
//				//   LOGGER.debug("success jsonObject:[" + jsonObject + "]");
//				if (jsonObject.get("scanCode") != null) {
//					try {
//						//   HttpSession session = req.getSession();
//						OrderResponse orderResponse = new OrderResponse();
//						orderResponse.setHmac(jsonObject.getString("hmac"));
//						orderResponse.setMerchantId(jsonObject.getString("merchantId"));
//						orderResponse.setRequestId(jsonObject.getString("requestId"));
//						orderResponse.setStatus(jsonObject.getString("status"));
//						String scanCodeStr = jsonObject.getString("scanCode");
//						orderResponse.setScanCode(Base64.decodeBase64(scanCodeStr));
//						System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
//						System.out.println(orderResponse.toString());
//						// session.setAttribute("orderResponse", orderResponse);
//						// resp.sendRedirect("scancode.jsp");
//					} catch (Exception e) {
//						e.printStackTrace();
//						// out.println("响应异常</br>");
//						// out.println(e.toString());
//					}
//				}else if(jsonObject.get("jsString") != null){
//					//微信公众号支付
//					System.out.println("=====================================");
//					try {
//						// HttpSession session = req.getSession();
//						// session.setAttribute("jsString", jsonObject.get("jsString"));
//						// resp.sendRedirect("wechatjsapi.jsp");
//					} catch (Exception e) {
//						//out.println("响应异常</br>");
//						// out.println(e.toString());
//					}
//				}
//				// out.println("提交成功</br>");
//				//out.println(jsonObject);
//			}

			public void redirect(JSONObject jsonObject, String redirectUrl) throws IOException {
				System.out.println("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
				System.out.println(redirectUrl);
				// resp.sendRedirect(redirectUrl);
				// LOGGER.debug("redirectUrl:[" + redirectUrl + "]");
				url[0] = redirectUrl;
			}


		});

		return url[0];
	}

	/**
	 * 代付提现
	 * @param payOnBehalf
	 * @return
	 */
	@Override
	public R<Map<String,String>> PayOnBehalf(PayOnBehalf payOnBehalf) {
		//校验用户支付密码
		Member member = remoteMemberService.findUserPayPassByUserId(payOnBehalf.getUserId(), SecurityConstants.FROM_IN);
		if(!member.getPayPass().equals(Rot.encode13(payOnBehalf.getPayPass()))){
			Map<String,String>m=new HashMap<>();
			m.put("status","FAILED");
			m.put("requestId",payOnBehalf.getRequestId());
			return R.failed(m,"支付密码不正确！");
		}
		SingleOrderBuilder builder = new SingleOrderBuilder(MERCHANT_ID);
		String plainString = new BigDecimal(payOnBehalf.getAmount()).multiply(BigDecimal.valueOf(100)).stripTrailingZeros().toPlainString();
		System.out.println(plainString+"--------------------------------------------------");
		builder.setAmount(plainString).setCurrency(ORDER_CURRENCY).setRequestId(payOnBehalf.getRequestId()).setNotifyUrl(PAY_ON_BEHALF_NOTIFY_URL);

		Payee payee1 = payOnBehalf.getPayee();
		//TransferDomesticPayee payee = BeanUtil.copyProperties(payOnBehalf.getPayee(), TransferDomesticPayee.class);
		TransferDomesticPayee payee = new TransferDomesticPayee();
		payee.setBankCardNum(payee1.getBankCardNum());
		payee.setName(payee1.getName());
		builder.setPayee(payee);
		System.out.println(builder.build()+"=========================");
		TransferDomesticSingleOrderExecuter executer = new TransferDomesticSingleOrderExecuter();

		Map<String,JSONObject> map=new HashMap<>();

		executer.bothOrder(builder,new ResultListenerAdpater(){
			/**
			 * 提交并支付成功,不代表转账成功
			 */
			@Override
			public void success(JSONObject jsonObject) {
				map.put("res",jsonObject);
				//System.out.println("支付结果"+jsonObject);
			}
		});
		JSONObject res = map.get("res");
		String requestId = res.getString("requestId");
		String status = res.getString("status");
		Map<String,String>m=new HashMap<>();
		m.put("requestId",requestId);
		m.put("status",status);
		return R.ok(m,"提现成功！");
	}

	@Override
	public PayOnBehalfRetuenVo findOnBehalfByOderId(String orderId) {
		QueryBuilder builder = new QueryBuilder(MERCHANT_ID);
		builder.setRequestId(orderId);
		TransferDomesticSingleOrderExecuter executer = new TransferDomesticSingleOrderExecuter();
		Map<String,JSONObject> m=new HashMap<>();

		executer.bothQuery(builder, new ResultListenerAdpater() {
			@Override
			public void success(JSONObject jsonObject) {
				m.put("res",jsonObject);
			}
		});
		PayOnBehalfRetuenVo payOnBehalfRetuenVo = JSON.toJavaObject(m.get("res"), PayOnBehalfRetuenVo.class);
		return payOnBehalfRetuenVo;
	}

	@Override
	public PayOrderResVo findPayOrderByOderId(String orderId) {
		com.upay.sdk.onlinepay.builder.QueryBuilder builder = new com.upay.sdk.onlinepay.builder.QueryBuilder(MERCHANT_ID);
		builder.setRequestId(orderId);
		OnlinePayOrderExecuter executer = new OnlinePayOrderExecuter();
		Map<String,JSONObject> m=new HashMap<>();
		executer.bothQuery(builder, new ResultListenerAdpater() {
					@Override
					public void success(JSONObject jsonObject) {
						m.put("res",jsonObject);
					}});
		PayOrderResVo res = JSON.toJavaObject(m.get("res"), PayOrderResVo.class);
		return res;
	}

	@Autowired
	private RabbitTemplate rabbitTemplate;

	@Override
	public void onChain(String requestId) {

		rabbitTemplate.convertAndSend("payQueueExchange", "pay", requestId);
	}

	public static void main(String[] args) {

		PayOnBehalf payOnBehalf = new PayOnBehalf();
		payOnBehalf.setAmount("100");
		payOnBehalf.setRequestId(UUID.randomUUID().toString().replace("-",""));
		Payee payee1 = new Payee();
		payee1.setBankCardNum("6214838766791976");
		payee1.setBranchBankName("昆明分行西园路支行");
		payee1.setName("金志勇");

		SingleOrderBuilder builder = new SingleOrderBuilder(MERCHANT_ID);
		builder.setAmount(payOnBehalf.getAmount()).setCurrency(ORDER_CURRENCY).setRequestId(payOnBehalf.getRequestId()).setNotifyUrl(PAY_ON_BEHALF_NOTIFY_URL);
		TransferDomesticPayee payee = new TransferDomesticPayee();
		payee.setBankCardNum(payee1.getBankCardNum());
		payee.setName(payee1.getName());
		builder.setPayee(payee);
		TransferDomesticSingleOrderExecuter executer = new TransferDomesticSingleOrderExecuter();

		Map<String,JSONObject> map=new HashMap<>();

		executer.bothOrder(builder,new ResultListenerAdpater(){
			/**
			 * 提交并支付成功,不代表转账成功
			 */
			@Override
			public void success(JSONObject jsonObject) {
				map.put("res",jsonObject);
				//System.out.println("支付结果"+jsonObject);
			}
		});
		JSONObject res = map.get("res");
		String requestId = res.getString("requestId");
		String status = res.getString("status");

	}


}
